# -*- coding: utf-8 -*-
import random
from datetime import datetime
from scrapy import Request
from scrapy.exceptions import IgnoreRequest
from scrapy.utils.project import get_project_settings
from zc_core.dao.item_pool_dao import ItemPoolDao
from zc_core.util.batch_gen import time_to_batch_no
from zc_core.util.http_util import retry_request
from zc_core.dao.batch_dao import BatchDao
from zc_core.util.done_filter import DoneFilter
from zc_core.dao.sku_pool_dao import SkuPoolDao
from zc_core.spiders.base import BaseSpider
from cpeinet.rules import *


class FullSpider(BaseSpider):
    name = "full"
    # 详情页url
    item_url = "http://emall.cpeinet.com.cn/visitor/goodsBuyer/goodsdetails.do?goodId={}"

    def __init__(self, batchNo=None, *args, **kwargs):
        super(FullSpider, self).__init__(batchNo=batchNo, *args, **kwargs)
        # 创建批次记录
        BatchDao().create_batch(self.batch_no)
        # 避免重复采集
        self.done_filter = DoneFilter(self.batch_no)

    def start_requests(self):
        settings = get_project_settings()
        # pool_list = ItemPoolDao().get_item_pool_list(
        #     fields={"_id": 1, "catalog3Id": 1, "catalog3Name": 1, 'offlineTime': 1},
        #     query={'catalog1Name': {'$in': ['办公耗材', '办公设备']}},
        # )
        pool_list = SkuPoolDao().get_sku_pool_list(
            fields={"_id": 1, "catalog3Id": 1, "catalog3Name": 1, 'offlineTime': 1})
        self.logger.info('全量：%s' % (len(pool_list)))
        dist_list = [x for x in pool_list if not self.done_filter.contains(x.get('_id'))]
        self.logger.info('目标：%s' % (len(dist_list)))
        random.shuffle(dist_list)
        for sku in dist_list:
            sku_id = sku.get("_id")
            catalog3_id = sku.get("catalog3Id")
            catalog3_name = sku.get("catalog3Name")
            item_url = self.item_url.format(sku_id)

            # 避免无效采集
            offline_time = sku.get('offlineTime', 0)
            if offline_time > settings.get('MAX_OFFLINE_TIME', 2):
                self.logger.info('忽略: [%s][%s]', sku_id, offline_time)
                continue
            # 避免重复采集
            if self.done_filter.contains(sku_id) and not settings.get('FORCE_RECOVER', False):
                self.logger.info('已采: [%s]', sku_id)
                continue
            yield Request(
                url=item_url,
                meta={
                    'reqType': 'item',
                    'skuId': sku_id,
                    'batchNo': self.batch_no,
                    'catalog3Id': catalog3_id,
                    'catalog3Name': catalog3_name,
                    'skuLink': item_url
                },
                callback=self.parse_item_data,
                errback=self.error_back
            )

    def parse_item_data(self, response):
        meta = response.meta
        sku_id = meta.get('skuId')
        item = parse_item_data(response)
        if item:
            self.logger.info('商品: [%s]' % sku_id)
            yield item
        else:
            self.logger.info('下架: [%s]' % sku_id)


